import React, { useEffect, useState } from 'react';
import { Space, Table, Button, Switch, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DelLevel, GetUserLevel } from '@/apis/user';
import AddUserLevel from '@/components/addUserLevel';
import UpdateUserLevel from '@/components/updateUserLevel'
import SearchLevel from '@/components/searchLevel'

// 表格约束
interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
}

type Props = {}

const Level = (props: Props) => {
    const [list, setList] = useState([])
    const [messageApi, contextHolder] = message.useMessage();
    const [visiable, setVisiable] = useState(false)
    const [update, setUpdate] = useState(false)
    const [item, setItem] = useState({})

    useEffect(() => { getAll() }, [])
    // 表格格式
    const columns: ColumnsType<DataType> = [
        { title: 'ID', dataIndex: '_id' },
        { title: '等级图标', dataIndex: 'icon', render: (img) => <img src={img} alt="" width='36px' height='36px' /> },
        { title: '等级背景图', dataIndex: 'image', render: (img) => <img src={img} alt="" width='36px' height='36px' /> },
        { title: '等级名称', dataIndex: 'name' },
        { title: '等级', dataIndex: 'grade' },
        { title: '享受折扣', dataIndex: 'discount' },
        {
            title: '是否显示', dataIndex: 'is_show',
            render: (show) => show ? <Switch checkedChildren="显示" unCheckedChildren="隐藏" defaultChecked onChange={onChange} /> : <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
        },
        {
            title: '操作', dataIndex: '',
            render: (text) => (
                <Space>
                    <a onClick={() => { setUpdate(true), setItem(text) }}>修改</a>
                    <a onClick={() => del(text._id)} >删除</a>
                </Space>)
        },
    ];
    // 显示回调
    const onChange = () => {
        messageApi.open({
            type: 'error',
            content: '没有权限',
        });
    }

    // 获取初始数据
    const getAll = async () => {
        const res: any = await GetUserLevel({})
        // console.log(res);
        setList(res.data)
    }
    // 模态框
    const close = (state: boolean) => {
        setVisiable(state)
        setUpdate(state)
        getAll()
    }
    const open = () => {
        setVisiable(true)
    }
    // 删除
    const del = async (_id: any) => {
        const res = await DelLevel({ _id })
        console.log(res);
        getAll()
    }
    // 搜索
    const search = (list: any) => { setList(list) }

    return (
        <>
            {contextHolder}
            <SearchLevel search={search} />
            <Button type='primary' onClick={open}> + 添加用户等级</Button>
            <Table columns={columns} dataSource={list} rowKey='_id' />
            <AddUserLevel visiable={visiable} close={close} />
            <UpdateUserLevel visiable={update} close={close} item={item} />
        </>
    )
}

export default Level